package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.dao.Order;
import com.itheima.entity.Result;
import com.itheima.service.IOrderService;
import com.itheima.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private IOrderService orderService;

    /**
     * 预约功能
     * @param map
     * @return
     */
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){
        String  telephone = (String) map.get("telephone");
        // 获得redis中验证码
        String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        // 获得页面验证码
        String  validateCode = (String) map.get("validateCode");

        if (validateCodeInRedis == null || validateCode == null || !validateCode.equals(validateCodeInRedis)){
            // 验证码输入有误
            return new Result(false,MessageConstant.VALIDATECODE_ERROR);
        }

        // 提交预约信息
        Result result = null;
        try {

            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            result = new Result(true,MessageConstant.ORDER_SUCCESS,orderService.add(map));
        } catch (Exception e) {
            e.printStackTrace();
            // 预约失败
            return new Result(false,MessageConstant.ORDER_FAIL);
        }


        if (result.isFlag()){
            //预约成功发送短信通知
            try {
                SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone, (String) map.get("orderDate"));
            } catch (ClientException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    /**
     * 成功页面回显
     * @param id
     * @return
     */
    @RequestMapping("/findById")
    public Result findById(Integer id){

        try {
            Map map = orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }

}
